import axios from 'axios'
import { getToken, removeToken } from './auth'
import { ElMessage, ElLoading } from 'element-plus'

let TIME_OUT = 20 * 1000
let loading = null
// 创建一个axios实例
const instance = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: TIME_OUT
})

// request
instance.interceptors.request.use(
  (req) => {
    // token setting
    const token = getToken()
    if(token){
      req.headers['Authorization'] = token
    }
    // eslint-disable-next-line no-cond-assign
    if (req.loading ??= true) {
      loading = ElLoading.service({
        text: '加载中',
        lock: true,
        background: 'transparent'
      })
    }
    return req
  },
  (err) => {
    Promise.reject(err)
  }
)

// 拦截返回的数据
instance.interceptors.response.use(response => {
  if (loading) loading.close()
  const { msg, code } = response.data
  if (code == '0') {
    return response.data
  } else {
    ElMessage({
      message: msg,
      type: 'error'
    })
    return Promise.reject(msg)
  }
}, error => {
  if (loading) loading.close()
  ElMessage({
    message: error,
    type: 'error'
  })
  if (error.response.status === 401 && import.meta.env.DEV) { // 未授权且开发模式下
    removeToken()
    location.reload()
  }
  return Promise.reject(error)
})

export default instance
